var http = require('http');
var url = require('url');
var qrstring = require('querystring');
function sendResponse(weatherData,res){
	var page = '<html><head><meta encode="utf-8"><title>http server External</title></head><body><form method="post">city:<input name="city"/><input type="submit" value="get Weather"/></form>';
	if(weatherData){
		page+='<div><h1>weather info</h1><p>'+weatherData+'</p></div>';
	}
	page+='</body></html>';
	res.end(page);
}
function parseWeather(weatherResponse,res){
	var responseData = '';
	weatherResponse.on('data',function(chunk){
		responseData+=chunk;
	});
	weatherResponse.on('end',function(){
		sendResponse(responseData,res);
	});
}
function getWeather(city,res){
	var options = {
		host:'localhost',
		port:8802
	};
	http.request(options,function(weatherResponse){
		parseWeather(weatherResponse,res);
	}).end();
}
http.createServer(function(req,res){
	console.log(req.method);
	if(req.method=='POST'){
		var reqData = '';
		req.on('data',function(chunk){
			reqData+=chunk;
		});
		req.on('end',function(){
			var postParam = qrstring.parse(reqData);
			getWeather(postParam.city,res);
		});
	}
	else{
		sendResponse(null,res);
	}
}).listen(8081);